package com.zhucan.commodity.application.consumer;

import com.zhucan.commodity.infrastructure.db.repository.CommodityRepository;
import com.zhucan.common.order.event.OrderCreateEvent;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.support.Acknowledgment;
import org.springframework.stereotype.Component;

/**
 * @author zhuCan
 * @description
 * @since 2022-07-06 10:50
 **/
@Slf4j
@Component
@RequiredArgsConstructor
public class CommodityConsumer {

    private final CommodityRepository commodityRepository;

    @KafkaListener(topics = "order_event", groupId = "order_event_consumer")
    public void consumeOrderEvent(ConsumerRecord<String, OrderCreateEvent> record, Acknowledgment ack) {

        log.info("接收到消息:{}", record);

        OrderCreateEvent event = record.value();

        commodityRepository.findById(event.getCommodityId()).ifPresent(x -> {
                    x.setPurchaseTimes(x.getPurchaseTimes() + 1);
                    commodityRepository.save(x);
                }
        );

        ack.acknowledge();
    }
}
